package reflectionV2.dynamic_proxy;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reflectionV2.IUserDao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ChangLiang
 * @date 2020/3/18
 */
public class UserDaoProxy implements InvocationHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 目标对象
     */
    private Object target;

    public IUserDao bind(Object target) {
        this.target = target;
        return (IUserDao) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result;
        if (StringUtils.equals(method.getName(), "save")) {
            logger.info("begin transaction");
            result = method.invoke(target, args);
            logger.info("end transaction");
        } else {
            result = method.invoke(target, args);
        }
        return result;
    }
}
